package grpc

import (
	"context"
	"fmt"
	"log"
	"net"
	"time"

	"advertising/internal/app/grpc/protoc/advertisingc"
	"advertising/internal/app/grpc/service/advertising"

	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
)

// StartRobotGrpc 启动grpc服务
func StartGrpc(ctx context.Context, port string) {
	l, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer(
		grpc.KeepaliveParams(keepalive.ServerParameters{
			Time:    time.Second * 15,
			Timeout: time.Second * 10,
		}), // 保活参数
		// 客户端发送ping的限制策略
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			MinTime:             time.Second, // 发送ping的最小间隔
			PermitWithoutStream: true,
		}), // 客户端发送ping的策略
	)
	go func() {
		for {
			select {
			case <-ctx.Done():
				s.Stop()
				l.Close()
			default:
				time.Sleep(time.Second)
			}
		}
	}()
	advertisingc.RegisterAdvertisingServiceServer(s, &advertising.Server{})
	if err := s.Serve(l); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
